import React, { useState, useEffect, useRef } from 'react'
import { Toast, NavBar } from 'react-vant';
import { useNavigate } from 'react-router-dom'
import { Search } from 'react-vant';
import axios from '../../utils/index'
import { Sticky, Button } from 'react-vant'
import { Tabs, Cell, IndexBar, IndexAnchor } from 'react-vant'
import AMapLoader from "@amap/amap-jsapi-loader";
import './index.css'
const Index: React.FC = () => {
    const navigate = useNavigate()
    const [list, setList] = useState<any>([])
    const [searchTerm, setSearchTerm] = useState('');
    const listContainer = useRef(null);
    const aaa = async () => {
        const res = await axios.get('/api/city')
        if (res.data.code === 200) {
            setList(res.data.city)
            console.log(res.data.city, 'list');
        }
    }
    useEffect(() => {
        aaa()
    }, [])

    const handleSearch = async (value) => {
        const filteredData = list.filter((item: any) =>
            item.lists.some(listItem => listItem.toLowerCase().includes(value.toLowerCase())));
        console.log('搜索结果:', filteredData);
        setSearchTerm(filteredData[0].lists.filter((item: any) => item.toLowerCase().includes(value.toLowerCase())));
        console.log(filteredData[0].lists.filter((item: any) => item.toLowerCase().includes(value.toLowerCase())), 'filteredData');
    };


    const [shu, setShu] = useState(['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'])
    const Amap = useRef(null);
    const [cheng, setCheng] = useState([])
    const getGeo2 = () => {
        if (!Amap.current) return;
        const citysearch = new Amap.current.CitySearch();
        citysearch.getLocalCity(function (status, result) {
            if (status === "complete" && result.info === "OK") {
                if (result && result.city && result.bounds) {
                    var cityinfo = result.city;
                    var citybounds = result.bounds;
                    setCheng(cityinfo);
                    console.log(
                        cityinfo,
                        citybounds,

                         
                        "========================>获取定位成功"
                    );
                }
            } else {
                console.log("获取定位失败");
            }
        });
    };
    useEffect(() => {
        window._AMapSecurityConfig = {
            securityJsCode: "5de05e4ba4d7701be167e93a0bc3f33e",
        };
        AMapLoader.load({
            key: "820d0f4ddd5442b40e4571fae14aa9b5",
            version: "2.0",
            plugins: ["AMap.Scale", "AMap.CitySearch"],
        }).then((AMap) => {
            Amap.current = AMap;
            console.log(Amap.current, '========================>amap')

        }, []);
    }, []);


// 点击字母时的事件处理函数
const scrollToItem = (letter) => {
  // 构建目标元素的id
  const targetId = `${letter}1`; // 假设每个字母的第一个列表项id是字母+1
  // 获取目标元素
  const targetElement = document.getElementById(targetId);
  if (targetElement) {
    // 滚动到目标元素
    targetElement.scrollIntoView({ behavior: 'smooth' });
  }
};

    return (
        <div className='nn'>
            {/* <Sticky> */}
                <NavBar
                    title="选择地区"
                    onClickLeft={() => navigate(-1)}
                />
                <div>
                    <Search shape="round" clearable placeholder="请输入您想找城市的名称" value={searchTerm} onSearch={handleSearch} />
                    <Cell>{searchTerm.length > 0 && searchTerm.map((item, index) => (
                        <div key={index} onClick={() => {
                            localStorage.setItem('city', item)
                            navigate(-1)
                        }}>{item}</div>
                    ))}</Cell>
                </div>
            {/* </Sticky> */}

            <div>
                <button onClick={getGeo2}>点击获取当前位置信息</button>&nbsp;
                当前城市：<span onClick={()=>{
                    localStorage.setItem('city',cheng)
                    navigate(-1)
                }} style={{color:'#1e99ff'}}>{cheng}</span>
            </div>

            <div className='dd'>
                {
                    shu.map((item: any, index: number) => (
                        <div key={index} className='ee' onClick={() => scrollToItem(item)}>{item}</div>
                    ))
                }
            </div>
            {
                list.map((item: any, index: number) => (
                    <div key={index}>
                        <div className='cc'>{item.title}</div>
                        <div>
                            {item.lists.map((v: any, i: number) => (
                                <div key={i} id={`${item.title[0]}${i+1}`} className='aa'>
                                    <Cell onClick={() => {
                                        localStorage.setItem('city', v)
                                        navigate(-1)
                                    }}>{v}</Cell>
                                </div>
                            ))}
                        </div>
                    </div>
                ))
            }
        </div>
    )
}

export default Index
